package com.hengxinguotong.hxgtwygsp.net;

import com.google.gson.Gson;
import com.hengxinguotong.hxgtwygsp.BuildConfig;
import com.hengxinguotong.hxgtwygsp.utils.Algorithm;
import com.hengxinguotong.hxgtwygsp.utils.MimeUtil;
import com.hengxinguotong.hxgtwygsp.utils.PreferencesUtil;
import com.jakewharton.retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;

import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * TODO
 *
 * @author hjz
 * @version V1.0.0
 * @since 2018/8/30 16:25
 *
 * 20181225
 */

public class BaseRequest
{
    protected static final String TESTMODE = "TestMode";
    protected static final String SERVER_ERROR = "系统异常";
    protected static final int SUCCESS_CODE = 200;

    private static final String KEY = "xXO00o1=";
    private static final String BASE_FILE_HOST = "http://m.escst.com/";
    private static final String BASE_URL = "http://t.weather.sojson.com/";
    private static final String TEST_BASE_URL = "http://t.weather.sojson.com/";

    protected Gson gson;
    protected boolean testMode;//测试模式

    public BaseRequest(PreferencesUtil preferencesUtil, Gson gson)
    {
        this.gson = gson;
        this.testMode = BuildConfig.DEBUG && preferencesUtil.contain(TESTMODE);
    }

    /**
     * 创建Retrofit实例
     *
     * @param testMode
     * @return retrofit2.Retrofit
     * @author hjz
     * @since 2018/10/16 15:53
     */
    protected Retrofit createRetrofit(boolean testMode)
    {
        String realUrl = testMode ? TEST_BASE_URL : BASE_URL;
        return new Retrofit.Builder()
                .baseUrl(realUrl) //设置网络请求的Url地址
                .client(ClientFactory.create(realUrl))
                .addConverterFactory(GsonConverterFactory.create()) //设置数据解析器
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build();
    }

    /**
     * 转multipart请求体
     *
     * @param params
     * @param files
     * @param method
     * @return okhttp3.MultipartBody
     * @author hjz
     * @since 2018/10/16 15:09
     */
    protected MultipartBody toMultipartBody(Map<String, Object> params, Map<String, File> files, String method)
    {
        MultipartBody.Builder builder = new MultipartBody.Builder();
        builder.setType(MultipartBody.FORM);
        Map<String, String> mParams = enParams(params, method);
        Set<Map.Entry<String, String>> paramSet = mParams.entrySet();
        for (Map.Entry<String, String> entry : paramSet)
        {
            builder.addFormDataPart(entry.getKey(), entry.getValue());
        }
        Set<Map.Entry<String, File>> fileSet = files.entrySet();
        File file;
        for (Map.Entry<String, File> entry : fileSet)
        {
            file = entry.getValue();
            if (file != null && file.exists())
            {
                MediaType mediaType = MediaType.parse(MimeUtil.guessMimeType(file.getAbsolutePath()));
                RequestBody requestBody = RequestBody.create(mediaType, file);
                builder.addFormDataPart("filename", file.getName(), requestBody);
            }
        }
        return builder.build();
    }

    protected MultipartBody toMultipartBody(Map<String, Object> params, File file, String method)
    {
        MultipartBody.Builder builder = new MultipartBody.Builder();
        builder.setType(MultipartBody.FORM);
        Map<String, String> mParams = enParams(params, method);
        Set<Map.Entry<String, String>> paramSet = mParams.entrySet();
        for (Map.Entry<String, String> entry : paramSet)
        {
            builder.addFormDataPart(entry.getKey(), entry.getValue());
        }
        if (file != null && file.exists())
        {
            MediaType mediaType = MediaType.parse(MimeUtil.guessMimeType(file.getAbsolutePath()));
            RequestBody requestBody = RequestBody.create(mediaType, file);
            builder.addFormDataPart("filename", file.getName(), requestBody);
        }
        return builder.build();
    }

    /**
     * 参数加密
     *
     * @param paramMap
     * @param method
     * @return java.util.Map<java.lang.String,java.lang.String>
     * @author hjz
     * @since 2018/10/16 15:16
     */
    protected Map<String, String> enParams(Map<String, Object> paramMap, String method)
    {
        String params = gson.toJson(paramMap);
        System.out.println("========================");
        System.out.println(method);
        System.out.println(params);
        System.out.println("========================");
        String mParams = Algorithm.DesEncryptECB(params, KEY);
        String token = Algorithm.Md5Encrypt(KEY + mParams + KEY);
        Map<String, String> map = new HashMap<>();
        map.put("url", method);
        map.put("parameter", mParams);
        map.put("accesstoken", token);
        return map;
    }

    //    /**
//     * 获取http请求头字符串
//     *
//     * @param user
//     * @param method
//     * @return java.lang.String
//     * @author hjz
//     * @since 2018/10/16 15:19
//     */
//    protected String getHeader(User user, String method)
//    {
//        String header;
//        String platappkey = "";
//        String plattoken = "";
//        if (user != null && !(Method.UserLogin.equals(method)
//                || Method.UserPhoneCode.equals(method)
//                || Method.UserPhoneUserauthentication.equals(method)
//                || Method.UserPhoneSend.equals(method)
//                || Method.UserPasswordSave.equals(method)))
//        {
//            platappkey = user.getPlatappkey();
//            plattoken = user.getPlattoken();
//        }
//        long timestamp = System.currentTimeMillis();
//        Map<String, String> token = new HashMap<>();
//        token.put("platappkey", platappkey);
//        token.put("plattoken", plattoken);
//        token.put("timestamp", String.valueOf(timestamp));
//        String des = Algorithm.DesEncryptECB(platappkey + plattoken + timestamp, KEY);
//        token.put("parasecrect", des);
//        header = Algorithm.DesEncryptECB(GsonUtil.INSTANCE.toJson(token), KEY);
//        return header;
//    }
//
    protected String getTestHeader()
    {
        String header;
        String platappkey = "zhesh_f97764222c234726a99735c";
        String plattoken = "4edfd9aee1f04d608fbf4eb717f8a39b";
        long timestamp = System.currentTimeMillis();
        Map<String, String> token = new HashMap<>();
        token.put("platappkey", platappkey);
        token.put("plattoken", plattoken);
        token.put("timestamp", String.valueOf(timestamp));
        String des = Algorithm.DesEncryptECB(platappkey + plattoken + timestamp, KEY);
        token.put("parasecrect", des);
        header = Algorithm.DesEncryptECB(gson.toJson(token), KEY);
        return header;
    }
}
